package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.ui.SpanBean
import io.gitee.kotle.player.ui.getCountTimeByLong
import io.gitee.kotle.player.ui.setInvisible
import io.gitee.kotle.player.ui.textFromSpanBean

/**
 * 调节声音和亮度的提示文字
 */
open class ExoPlayerCenterHintText : AppCompatTextView, IExoPlayerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private var _player: IPlayer<MediaItem, IExoPlayerMode>? = null
    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        _player = player
        config.currentVolume.observeForever(::onVolumeChange)
        config.screenBrightness.observeForever(::onScreenBrightnessChange)
        config.seekBarProgress.observeForever(::onSeekBarProgress)
    }


    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        _player = null
        config.currentVolume.removeObserver(::onVolumeChange)
        config.screenBrightness.removeObserver(::onScreenBrightnessChange)
        config.seekBarProgress.removeObserver(::onSeekBarProgress)
    }


    open fun onVolumeChange(fl: Float?) {
        setInvisible(fl != null)
        if (fl != null) {
            text = "音量 ${(fl * 100).toInt()}%"
        }
    }

    open fun onScreenBrightnessChange(fl: Float?) {
        setInvisible(fl != null)
        if (fl != null) {
            text = "亮度 ${(fl * 100).toInt()}%"
        }
    }


    open fun onSeekBarProgress(pair: Pair<Boolean, Float>?) {
        setInvisible(pair?.first == false)
        pair?.second?.let {
            val spans = mutableListOf<SpanBean>()
            spans.add(SpanBean("进度 ${(it * 100).toInt()}%"))
            val totalMs = _player?.duration
            if (totalMs != null) {
                spans.add(
                    SpanBean(
                        "\n${getCountTimeByLong((totalMs * it).toLong())}/${
                            getCountTimeByLong(
                                totalMs
                            )
                        }",
                        textSize = 10
                    )
                )
            }
            textFromSpanBean(spans)
        }
    }
}